//
//  VideoViewController.m
//  Comic
//
//  Created by Andy.He on 16/3/10.
//  Copyright © 2016年 程锦. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoPlayer.h"

#define URL @"http://s.budejie.com/topic/list/zuixin/41/baisishequ-iphone-4.0/0-20.json"
#define LOADURL @"http://s.budejie.com/topic/list/zuixin/41/baisishequ-iphone-4.0/%@-20.json"

@interface VideoViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *select_CollectionView;
@property(nonatomic,strong)UICollectionView *main_CollectionView;

@property(nonatomic,strong)NSString *timestamp;

@property(nonatomic,strong)NSMutableArray *list_Arr;

@property(nonatomic,strong)VideoPlayer *player;

@property(nonatomic,assign)CGFloat item_width;

@property(nonatomic,strong)NSNumber *np;

@end

@implementation VideoViewController


- (void)viewWillDisappear:(BOOL)animated{

    
    [[VideoPlayer shareInstance].player pause];
    [[VideoPlayer shareInstance].playerLayer removeFromSuperlayer];
    [[VideoPlayer shareInstance].rePlay setHidden:YES];
    [[VideoPlayer shareInstance].backView removeFromSuperview];
    [[VideoPlayer shareInstance].maskView removeFromSuperview];



}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
//    self.title = @"暴走视频";
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970];
    self.timestamp = [NSString stringWithFormat:@"%.0f", a];
    
    
    
    self.view.backgroundColor = [UIColor colorWithRed:0.9424 green:0.9333 blue:0.9516 alpha:1.0];
    
    [self createData];
    
    
    [self createCollectionView];
    
    [self.select_CollectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    
    
    [self listeningRotating];
   
}






#pragma mark 解析数据

- (void)createData{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    [manager GET:URL parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr= [NSArray arrayWithArray:responseObject[@"list"]];
        
        self.np = responseObject[@"info"][@"np"];
        
        self.list_Arr = [NSMutableArray array];

        
        for (NSDictionary *dic in arr) {
            VideoModel *model = [[VideoModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.list_Arr addObject:model];
        }
        
        [self.main_CollectionView.mj_header endRefreshing];

        [self.main_CollectionView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        
    }];
   
    
}

- (void)loadData{

    
    
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    
    [manager GET:[NSString stringWithFormat:LOADURL,self.np] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        self.np = responseObject[@"info"][@"np"];

        
        NSArray *arr= [NSArray arrayWithArray:responseObject[@"list"]];
        
        
        for (NSDictionary *dic in arr) {
            VideoModel *model = [[VideoModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.list_Arr addObject:model];
        }
        
        
        [self.main_CollectionView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"%@",error);
        
    }];
    

    
    
    


}


#pragma mark 创建瀑布流
- (void)createCollectionView{
    
    //选择瀑布流
    UICollectionViewFlowLayout *select_FlowLayout = [UICollectionViewFlowLayout new];
    
//    select_FlowLayout.itemSize = CGSizeMake(SCREEN_WIDTH/2.0, 35);
    
    select_FlowLayout.minimumLineSpacing = 0;
    select_FlowLayout.minimumInteritemSpacing = 0;
    
    
    self.select_CollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:select_FlowLayout];
    
    self.select_CollectionView.scrollEnabled = NO;
    
    [self.view addSubview:self.select_CollectionView];
    
    
    [self.select_CollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.top.left.right.mas_equalTo(0);
        
        make.height.mas_equalTo(0);
        
    }];
    
    
    
    //设置代理人
    self.select_CollectionView.delegate = self;
    self.select_CollectionView.dataSource = self;
    
    //注册
    
    [self.select_CollectionView registerClass:[SelectCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([SelectCollectionViewCell class])];
    
    
    
    //main_collectionView
    
    UICollectionViewFlowLayout *main_FlowLayout = [UICollectionViewFlowLayout new];
    
    
    
    main_FlowLayout.minimumLineSpacing = 10;
    
    self.main_CollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:main_FlowLayout];
    
    self.main_CollectionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.main_CollectionView];
    
    
    [self.main_CollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        
        make.top.mas_equalTo(self.select_CollectionView.mas_bottom).offset(0);
        make.left.right.bottom.mas_equalTo(0);
        
    }];
    
    
    
    [self.main_CollectionView registerClass:[MainCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MainCollectionViewCell class])];
    
    
    
    self.main_CollectionView.delegate = self;
    
    self.main_CollectionView.dataSource = self;
    
   self.main_CollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshing)];
    
    self.main_CollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footloading)];
    
    
    
    
    
}
- (void)refreshing{
    
    [self createData];

}

- (void)footloading{
    
    [self loadData];
    
    self.main_CollectionView.mj_footer.hidden = YES;
    
    [self.main_CollectionView.mj_footer endRefreshing];

    self.main_CollectionView.mj_footer.hidden = NO;
}

#pragma mark 瀑布流协议方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    if (collectionView == self.select_CollectionView) {
        return 2;
    }else{
        
//        self.main_CollectionView.mj_footer.hidden = self.list_Arr.count;
        
        return self.list_Arr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == self.select_CollectionView) {
        
        SelectCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SelectCollectionViewCell class]) forIndexPath:indexPath];
        
        cell.backgroundColor = [UIColor colorWithRed:0.9424 green:0.9333 blue:0.9516 alpha:1.0];
        
        cell.title_Label.highlightedTextColor = [UIColor redColor];
        
        switch (indexPath.row) {
            case 0:
                cell.title_Label.text = @"最新更新";
                break;
            case 1:
                cell.title_Label.text = @"全部视频";
                break;
            default:
                break;
        }
        
        
        return cell;
    }else{
        
        MainCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([MainCollectionViewCell class]) forIndexPath:indexPath];
        
        VideoModel *model = self.list_Arr[indexPath.row];
        
        
        cell.user_Login.text = model.u[@"name"];
        cell.title.text = model.text;
        
        [cell.user_Avatar setImageWithURL:[NSURL URLWithString:model.u[@"header"][0]]];
        
        cell.published.text = model.passtime;
        
        
        NSArray *arr = [NSArray arrayWithArray:model.tags];
        
        NSMutableString *tags_Str = [NSMutableString string];
        
        for (NSDictionary *dic in arr) {
            [tags_Str insertString:[NSString stringWithFormat:@"  "@"%@",dic[@"name"]] atIndex:0];
        }
        
        
        cell.tags_Label.text = tags_Str;
        
        [[VideoPlayer shareInstance].player pause];
        [[VideoPlayer shareInstance].playerLayer removeFromSuperlayer];
        [[VideoPlayer shareInstance].rePlay setHidden:YES];
        [[VideoPlayer shareInstance].backView removeFromSuperview];
        [[VideoPlayer shareInstance].maskView removeFromSuperview];

        
        cell.url = [model.video[@"video"] firstObject];
        


        [cell.mp4_ImageView setImageWithURL:[model.video[@"thumbnail"] firstObject] placeholderImage:[UIImage imageNamed:@"fakeimg"]];
        

        
        return cell;
        
    }
    
    
    
}



- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    
    if (collectionView == self.main_CollectionView) {
        VideoModel *model = self.list_Arr[indexPath.row];
        
        CGFloat height = [model.video[@"height"] floatValue];
        
        CGFloat width = [model.video[@"width"] floatValue];

        
        
        CGFloat item_height = height * (SCREEN_WIDTH - 20) /width;
        
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:15],NSFontAttributeName, nil];
        //根据文本的内容和文本的字体,进行计算高度
        //参数1:告诉系统,文本显示的最大范围
        CGRect rect1 = [model.text boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        CGRect rect2 = [[model.tags firstObject][@"name"] boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
  
        
        
        return CGSizeMake(SCREEN_WIDTH,85+ rect2.size.height + rect1.size.height + item_height);
    }else{
    
        return CGSizeMake(SCREEN_WIDTH/2.0, 35);
    }
    
   
}



- (void)listeningRotating{
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onDeviceOrientationChange)
                                                 name:UIDeviceOrientationDidChangeNotification
                                               object:nil
     ];
    
}


- (void)onDeviceOrientationChange{
    
    
    [self.main_CollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.mas_equalTo(self.select_CollectionView.mas_bottom).offset(0);
        make.left.right.bottom.mas_equalTo(0);
        
    }];
    
    
    [self.main_CollectionView reloadData];
}

- (void)updateViewConstraints {
    [self.main_CollectionView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(self.select_CollectionView.mas_bottom).offset(0);
        make.left.right.bottom.mas_equalTo(0);
        
    }];

    
    [self.main_CollectionView reloadData];
    
    [super updateViewConstraints];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
